<?php
// 设计师小助手自动回复答案
namespace Frieza\Modules\Autoreply\Controllers;

use App\Http\Controllers\Controller;
use Doraemon\model\Message\AutoReply;
use Doraemon\tools\ImgUrl;
use Doraemon\tools\LinkFormat;
use Encore\Admin\Actions\Interactor\Dialog;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class DesignerAnswerController extends Controller {

    // 新增/修改地区信息
    public function edit(Request $request, Content $content, $id = 0) {
        $request = $request->all();
        if (!$id) {
            $isCreate = true;
            $header = '回复新增';
        } else {
            $isCreate = false;
            $header = '回复修改';
        }
        $tab = new Tab();
        $tab->add($header, self::editAction($request, $id, $isCreate));
        return $content->header($header)
            ->breadcrumb(
                [
                    'text' => '自动回复',
                    'url' => route('designer_question.list')
                ],
                ['text' => '设计师小助手'],
                ['text' => $header]
            )->row($tab);
    }

    public function editAction($request, $id = 0, $isCreate = false) {
        if ($isCreate) {
            $data = [];
            $form = new Form($data);
            $queryParams = "?question_id={$request['question_id']}";
        } else {
            $queryParams = '';
            $data = AutoReply::get('*', ['id' => $id]);
            if ($data['reply_type'] == AutoReply::REPLY_LINK) {
                $data['reply_title_link'] = $data['reply_title'];
                $data['reply_link_info_link'] = json_decode($data['reply_link_info'], true);
            } else if ($data['reply_type'] == AutoReply::REPLY_IMG) {
                $data['reply_link_info_pic'] = $data['reply_link_info'];
            } else {
                $data['reply_title_txt'] = $data['reply_title'];
            }
            $form = new Form($data);
            $form->text('id', 'ID')->readOnly();
        }

        $form->select('reply_type', '回复类型')
            ->options(AutoReply::REPLY_TYPE_TXT)
            ->when(AutoReply::REPLY_TEXT, function (Form $form) {
                $form->textarea('reply_title_txt', '回复内容')->rules('required');
            })
            ->when(AutoReply::REPLY_IMG, function (Form $form) {
                $form->imgUpload('reply_link_info_pic', '图片')->help('单图')->rules('required');;
            })
            ->when(AutoReply::REPLY_LINK, function (Form $form) {
                $form->textarea('reply_title_link', '回复内容')
                    ->rules('required')
                    ->help('链接的回复内容必须以 【链接对应文案内容】 该种形式，例如：整屋案例的例子【小美的整屋】');
                $form->multiLinkSelect('reply_link_info_link', '链接')->rules('required');
            })
        ;
        $form->text('data_sort', '顺序')
            ->options(AutoReply::STATUS_TXT)
            ->default(AutoReply::STATUS_HIDDEN);
        $form->select('data_status', '状态')
            ->options(AutoReply::STATUS_TXT)
            ->default(AutoReply::STATUS_HIDDEN)
            ->required();
        $form->confirm('确认提交吗？');
        $form->action("/admin/autoreply/designer/answer/save{$queryParams}");
        return $form->render();
    }

    public function save(Request $request) {
        $request = $request->all();
        if ($request['reply_type'] == AutoReply::REPLY_TEXT && empty($request['reply_title_txt'])) {
            $error = new MessageBag(['title' => '请填写回复内容']);
            return back()->with(compact('error'));
        }
        if ($request['reply_type'] == AutoReply::REPLY_IMG && empty($request['reply_link_info_pic'])) {
            $error = new MessageBag(['title' => '请选择图片']);
            return back()->with(compact('error'));
        }
        if ($request['reply_type'] == AutoReply::REPLY_LINK) {
            if (empty($request['reply_title_link'])) {
                $error = new MessageBag(['title' => '请填写回复内容']);
                return back()->with(compact('error'));
            }
            $linkParams = $request['reply_link_info_link']['link_params'] ?? [];
            if (empty(array_filter($linkParams))) {
                $error = new MessageBag(['title' => '请填写链接']);
                return back()->with(compact('error'));
            }
        }
        if (!empty($request['reply_link_info_link'])) {
            $replyLink = LinkFormat::generateLink(
                $request['reply_link_info_link']['link_type'],
                json_encode($request['reply_link_info_link']['link_params'])
            );
            $replyLink = $replyLink['app_template'];
            $request['reply_link_info'] = json_encode($request['reply_link_info_link']);
        } else if (!empty($request['reply_link_info_pic'])) {
            $replyLink = ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $request['reply_link_info_pic'], ImgUrl::IMAGE_SIZE_SQ_PHONE);
            $request['reply_link_info'] = $request['reply_link_info_pic'];
        }
        $request['reply_title'] = '';
        if (!empty($request['reply_title_txt'])) {
            $request['reply_title'] = $request['reply_title_txt'];
        }
        if (!empty($request['reply_title_link'])) {
            $request['reply_title'] = $request['reply_title_link'];
        }
        $data = [
            'reply_title' => $request['reply_title'],
            'reply_type' => $request['reply_type'],
            'reply_link' => $replyLink ?? '',
            'reply_link_info' => $request['reply_link_info'] ?? '',
            'data_sort' => $request['data_sort'],
            'admin_uid' => Admin::user()->id,
            'data_status' => $request['data_status']
        ];
        if (isset($request['id'])) {
            $questionId = AutoReply::get('question_id', ['id' => $request['id']]);
            $questionInfo = AutoReply::get('*', ['id' => $questionId]);
            $replyCnt = AutoReply::count(['question_id' => $questionId, 'data_status' => AutoReply::STATUS_NORMAL]);
            if ($questionInfo['data_status'] == AutoReply::STATUS_NORMAL && $replyCnt == 1 && in_array($request['data_status'], [AutoReply::STATUS_HIDDEN, AutoReply::STATUS_DELETE])) {
                $error = new MessageBag(['title' => '仅剩余一个显示中的回复了，请先隐藏问题后再操作']);
                return back()->with(compact('error'));
            }
            $rs = AutoReply::updateInfo($data, ['id' => $request['id']]);
        } else {
            if (!AutoReply::get('*', ['id' => $request['question_id'], 'question_id' => 0])) {
                $error = new MessageBag(['title' => '该问题不存在']);
                return back()->with(compact('error'));
            }
            if ($request['reply_title']) {
                if (AutoReply::get('*', ['reply_title' => $request['reply_title'], 'question_id' => $request['question_id']])) {
                    $error = new MessageBag(['title' => '该问题下已经存在该回复']);
                    return back()->with(compact('error'));
                }
            }
            $data['question_id'] = $request['question_id'];
            $rs = AutoReply::addInfo($data);
        }
        $title = isset($request['id']) ? '修改成功' : '添加成功';
        if (!$rs) {
            $error = new MessageBag(['title' => $title]);
            return back()->with(compact('error'));
        }
        $success = new MessageBag(['title' => $title]);
        return redirect('/admin/autoreply/designer/question')->with(compact('success'));
    }


}
